package com.example.userservice.service.impl;

import com.example.userservice.config.RabbitMQConfig;
import com.example.userservice.model.event.OperationLogEvent;
import com.example.userservice.service.OperationLogService;
/*import jakarta.servlet.http.HttpServletRequest;*/
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;

/**
 * 操作日志服务实现（AI实现）
 */
@Slf4j
@Service
public class OperationLogServiceImpl implements OperationLogService {
    
    @Autowired
    private RabbitTemplate rabbitTemplate;
    
    @Override
    public void sendOperationLog(Long userId, String action, String detail, HttpServletRequest request) {
        String ip = getClientIp(request);
        OperationLogEvent event = new OperationLogEvent(userId, action, ip, detail);
        sendOperationLog(event);
    }
    
    @Override
    public void sendOperationLog(OperationLogEvent event) {
        try {
            rabbitTemplate.convertAndSend(
                RabbitMQConfig.OPERATION_LOG_EXCHANGE,
                RabbitMQConfig.OPERATION_LOG_ROUTING_KEY,
                event
            );
            log.info("操作日志消息发送成功: userId={}, action={}, ip={}", 
                    event.getUserId(), event.getAction(), event.getIp());
        } catch (Exception e) {
            log.error("操作日志消息发送失败: userId={}, action={}", 
                    event.getUserId(), event.getAction(), e);
        }
    }
    
    @Override
    public String getClientIp(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        // 处理多个IP的情况，取第一个IP
        if (ip != null && ip.contains(",")) {
            ip = ip.split(",")[0].trim();
        }
        return ip;
    }
}